import WidgetsManager from "@/core/Frame/Manager/WidgetsManager";
import EventsManager from "@/core/Frame/Manager/EventsManager";
import { screenFullEnter, exitsScreenFull, ToDegrees } from "@/utils/util";
import LayerManager from "@/core/PIEEarth/LayerManager";
import pointImg from "@/assets/pointImg/point2.png";
import { GlobeFlyTo } from "@/utils/CommonUtils";

import store from "@/store";

import {
  ref,
  readonly,
  provide,
  reactive,
  Ref,
  onUpdated,
  watch,
  onMounted,
} from "vue";
import sourceTab from "@/assets/PIEWorkSpace/sourceTab.png";
import layerTab from "@/assets/PIEWorkSpace/layerTab.png";

export const useHandler = () => {
  const EarthonLoad = ref(false);
  const isDataShow = ref(true);
  const isRightMenuShow = ref(false);
  const activeMenu = ref("文件");
  const groupList = ref([]);
  const mapView = ref(); //这个时候获取了子组件Comp
  const navigatorWarnShow = ref(false);
  const isDemonstration = ref(true);
  const activeName = ref("source");
  const isFullScreen = ref(true);

  let scale = ref(); //比例尺
  let lon = ref(); //jingdu
  let lat = ref(); //纬度
  let height = ref(); //高度
  let screenPoint = ref({}); //屏幕坐标

  let welcomeClose = ref(false);
  let myPercentage = ref(0);
  let isProgressShow = ref(true);

  let timer = setInterval(function () {
    if (myPercentage.value > 99) {
      closeProgressShow();
    } else {
      myPercentage.value += 10;
    }
  }, 300);

  let closeProgressShow = () => {
    welcomeClose.value = true;
    isProgressShow.value = false;
    myPercentage.value = 100;
    clearInterval(timer);
  };
  // watch(scale, (val: any) => {
  //   // scale = viewerInstance.getGlobe().getScale();
  //   handleCanvasMouseWheel();
  // });
  onMounted(() => {
    //监听鼠标滚动事件
    // window.addEventListener("mousewheel", handleCanvasMouseWheel, true);
    // welcomeClose.value = true;
    // isProgressShow.value = false;
    // myPercentage.value = 100;
    // clearInterval(timer);
  });

  //获取实时数据
  const handleCanvasMouseWheel = () => {
    if (viewerInstance) {
      let globe = viewerInstance.getGlobe();

      let scales = globe.getScale();
      scale.value = " 1 : " + Math.round(1 / scales);

      //获取场景地理坐标中心点
      let center = globe.getGeoCenter();
      let unitLon: any;
      let unitLat: any;
      if (center.x >= 0) {
        unitLon = "E";
      } else {
        unitLon = "W";
      }
      if (center.y >= 0) {
        unitLat = "N";
      } else {
        unitLat = "S";
      }
      lon.value = ToDegrees(Math.abs(center.x).toString(), unitLon);
      lat.value = ToDegrees(Math.abs(center.y).toString(), unitLat);

      const camera = globe.getWorldCamera();
      height.value = Math.round(camera.getDistance());

      //转换为屏幕坐标
      screenPoint.value = globe.mapToDevice(center);
      const spatialReference = globe.getSpatialReference();
      console.log(spatialReference.toWKT())

    }

  };
  const handleLayerTab = () => {
    activeName.value = "layer";
  };
  const handleSourceTab = () => {
    activeName.value = "source";
  };
  // const compName = ref('LocationPoint')
  window.onresize = function () {
    if (document.fullscreenElement) {
    } else {
      if (!isDemonstration.value) {
        isDemonstration.value = !isDemonstration.value;
      }
    }
  };
  // 浏览器版本警告显示
  const navigatorWarn = (flag: Boolean) => {
    navigatorWarnShow.value = true;
  };

  // 地球初始化状态
  provide("earthOnLoad", readonly(EarthonLoad));

  // 地球实例获取方法
  let viewerInstance: any = null;
  provide("getViewerInstance", () => {
    return viewerInstance;
  });

  // 消息管理器初始化
  const eventsManager = new EventsManager();
  provide("getEventsManager", () => {
    return eventsManager;
  });

  // console.log(store)
  // UI组件管理器初始化
  const widgets: Ref<any[]> = ref([]);
  const widgetsManager = new WidgetsManager();
  widgetsManager.init(widgets);
  provide("getWidgetsManager", () => {
    return widgetsManager;
  });

  // 监听地球加载，加载完成后改变地球初始化状态变量并给地球实例赋值
  const onload = (viewer: any) => {
    viewerInstance = viewer;
    EarthonLoad.value = true;
    eventsManager.on("layerChanged", (param: any) => {
      let LayerManagerObj = new LayerManager(viewer);
      let LayersEditLsit = LayerManagerObj.getLayersEditLsit();

      store.commit("changeEditList", LayersEditLsit);
    });
    handleCanvasMouseWheel();
    //tween动画的监听，否则飞行将不可用，勿删！！！wanggt注
    const PIETWEEN = window.PIETWEEN;
    viewer
      .getGlobeControl()
      .getPreRender()
      .addEventListener(() => {
        PIETWEEN.update();
      });
    closeProgressShow();
  };

  window.oncontextmenu = function (e) {
    //取消默认的浏览器自带右键 很重要！！
    e.preventDefault();
  };

  //适当的时机调用onsize事件解决球变瘦的问题
  onUpdated(() => {
    if (viewerInstance) {
      viewerInstance.getGlobeControl().onSize();
    }
  });

  //头部菜单栏
  const navChange = (item: any) => {
    activeMenu.value = item.name;
    groupList.value = item.groups;
  };
  //工作台tree点击事件
  const handleNodeClick = (node: any) => {
    console.log(node, "node");
    isRightMenuShow.value = false;
  };

  const zoomIn = () => {
    mapView.value.zoomIn();
  };
  const zoomOut = () => {
    mapView.value.zoomOut();
  };
  //退出全屏
  const exitScreenFull = () => {
    isFullScreen.value = !isFullScreen.value;
    exitsScreenFull();
  };
  //全屏
  const screenFullEnters = () => {
    isFullScreen.value = !isFullScreen.value;
    screenFullEnter();
  };
  //底部演示
  const demonstration = () => {
    screenFullEnter();
    isDemonstration.value = !isDemonstration.value;
  };
  //图层管理树结构
  const layerList = [
    {
      id: 1,
      icon: "icon-tuceng",
      label: "基础图层",
    },
    {
      id: 1,
      icon: "icon-datafull",
      label: "googleimageGE",
    },
  ];
  const PIE = window.PIE;
  let pointLayer: any;
  //加载点(添加图标文字)
  const addPoint = (location: any, name: any) => {
    const iconID = 5;
    const geometryID = 17;
    let globe = viewerInstance.getGlobe();

    //飞行定位
    const targetLon = Number(location[0]);
    const targetLat = Number(location[1]);
    const targetHeight = 10000;
    const time = 4 * 1000;
    GlobeFlyTo(globe, targetLon, targetLat, targetHeight, time); //飞行定位

    const workspace = globe.getDocument();
    const spatialReference = globe.getSpatialReference(); //获取空间参考系对象
    let globeLayer = new PIE.GlobeRenderableLayer(); //创建绘制对象图层
    globe.addLayer(globeLayer, true);

    /**创建线集合对象，添加在图层中**/
    let options = {
      url: pointImg,
      id: iconID,
      name: "test",
    };

    let pointText = spatialReference.forward(location); //将经纬度坐标转换为当前空间坐标系下的坐标
    let iconSymbol = new PIE.IconSymbol(); //图标符号操作
    let symbolLib = workspace.getSymbolLib();
    let symbolGroup = symbolLib.getGroup(PIE.SymbolGroupType.Icon);

    iconSymbol.load(options).then((value: any) => {
      symbolGroup.add(value); //value为成功设置name、id的iconSymbol，可将该符号对象添加至符号组中

      const text = new PIE.Text({
        point: pointText,
        text: name,
        ID: geometryID,
      }); //创建文本对象
      /** 文本渲染样式 **/
      const renderText = new PIE.RenderText({
        text: text,
        color: [255, 255, 255, 255],
        width: 14,
        height: 14,
        align: PIE.TextAlignType.Center,
      });

      //创建几何风格对象
      const vectorStyle = new PIE.VectorStyle({
        pointType: PIE.PointType.Icon, //设置点符号类型
        pointStyle: iconID, //点图标样式，与上方设置符号属性ID保持一致
        pointSize: [32, 32], //设置点符号标识大小
        pointAlign: PIE.PointAlignType.RightCenter, //设置点符号对齐方式
      });

      const textStyle = new PIE.TextStyle();
      textStyle.setForeColor([255, 255, 0, 255]);
      textStyle.setAlign(PIE.TextAlignType.LeftCenter);
      text.setTextStyle(textStyle);
      textStyle.dispose(); //风格对象内部会进行克隆，此处需要进行释放

      renderText.setStyle(vectorStyle); //几何对象风格
      globeLayer.add(renderText); //添加文本对象
      verticalAlign(geometryID, globeLayer);
    });
  };
  //图标文字样式
  const verticalAlign = (geometryID: any, globeLayer: any) => {
    const renderText = globeLayer.get(geometryID); //根据id获取绘制对象
    const vectorStyle = renderText.getStyle(); //获取几何对象风格
    vectorStyle.setPointAlign(PIE.PointAlignType.BottomCenter);
    renderText.setStyle(vectorStyle); //设置几何对象风格

    let text = renderText.getFeature().getGeometry(); //获取几何对象
    const textStyle = text.getTextStyle();
    textStyle.setAlign(PIE.TextAlignType.TopCenter);
    text.setTextStyle(textStyle);

    globeLayer.updateGeometry(text); //要素图层渲染器更新几何对象
    pointLayer = globeLayer;
  };
  //地名搜索
  const flyToLoad = (row: any) => {
    if (pointLayer) {
      pointLayer.remove(17);
    }
    let location = row.location.split(",");
    addPoint(location, row.name);
  };

  //---------------------------------大数据面板相关------------------------------------
  const isBigData = ref(false);

  function handleSwitchBigData() {
    isBigData.value = !isBigData.value;
  }

  return {
    mapView,
    activeMenu,
    isRightMenuShow,
    groupList,
    isDataShow,
    EarthonLoad,
    widgets,
    layerList,
    handleNodeClick,
    navChange,
    onload,
    zoomOut,
    zoomIn,
    isFullScreen,
    screenFullEnters,
    exitScreenFull,
    navigatorWarn,
    navigatorWarnShow,
    isDemonstration,
    demonstration,
    activeName,
    handleLayerTab,
    handleSourceTab,
    sourceTab,
    layerTab,
    flyToLoad,
    lat,
    lon,
    handleCanvasMouseWheel,
    scale,
    height,
    screenPoint,
    welcomeClose,
    myPercentage,
    isProgressShow,
    isBigData,
    handleSwitchBigData,
  };
};
